// 本地数据管理器会在需要时引入

Page({
  data: {
    matchList: [],
    filteredList: [],
    activeTab: 0,
    showDeleteIndex: null,
    safeTop: 100, // 默认100rpx，防止初次渲染被挡
    userInfo: null,
    allCount: 0,
    createdCount: 0,
    joinedCount: 0
  },
  onLoad() {
    // 动态获取胶囊菜单底部高度
    const menuButton = wx.getMenuButtonBoundingClientRect();
    this.setData({ safeTop: menuButton.bottom + 10 }); // 10rpx缓冲
  },
  onShow() {
    // 获取用户信息（可能为空）
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({ userInfo });
    console.log('【onShow】userInfo:', userInfo);
    
    try {
      // 引入本地数据管理器
      const localDataManager = require('../../utils/localDataManager.js');
      
      // 从本地存储加载数据
      const raceList = localDataManager.getAllRaces();
      
      // 过滤出当前用户的比赛
      let userRaceList = [];
      if (userInfo && userInfo.userId) {
        userRaceList = raceList.filter(race => {
          // 检查是否是自己创建的
          const isCreated = race.creator && race.creator.userId === userInfo.userId;
          // 检查是否是自己报名的
          const raceSignups = localDataManager.getSignups(race.id || race._id);
          const isSigned = raceSignups.some(signup => signup.userId === userInfo.userId);
          return isCreated || isSigned;
        });
      }
      
      // 处理比赛数据
      const matchList = userRaceList.map(race => {
        let dateStr = '';
        if (race.createdAt) {
          const dateObj = new Date(race.createdAt);
          dateStr = `${dateObj.getFullYear()}-${(dateObj.getMonth()+1).toString().padStart(2,'0')}-${dateObj.getDate().toString().padStart(2,'0')}`;
        }
        
        // 统计报名人数
        const raceSignups = localDataManager.getSignups(race.id || race._id);
        const appliedCount = raceSignups.length;
        const maxPlayers = race.maxPlayers || 8;
        
        // 检查是否本人报名
        const isSigned = raceSignups.some(signup => signup.userId === userInfo.userId);
        
        // 创建新对象，复制race的所有属性
        const raceItem = {};
        for (let key in race) {
          if (race.hasOwnProperty(key)) {
            raceItem[key] = race[key];
          }
        }
        
        // 添加额外属性
        raceItem._id = race.id; // 保持兼容性
        raceItem._openid = race.creator ? race.creator.userId : null;
        raceItem.dateStr = dateStr;
        raceItem.appliedCount = appliedCount;
        raceItem.maxPlayers = maxPlayers;
        raceItem.isSigned = isSigned;
        
        return raceItem;
      });
      
      // 按创建时间排序
      matchList.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
      
      // 统计数量
      const allCount = matchList.length;
      const createdCount = userInfo && userInfo.userId ? matchList.filter(item => item.creator && item.creator.userId === userInfo.userId).length : 0;
      const joinedCount = matchList.filter(item => item.isSigned).length;
      
      console.log('【onShow】统计 allCount:', allCount, 'createdCount:', createdCount, 'joinedCount:', joinedCount);
      
      this.setData({ 
        matchList, 
        allCount, 
        createdCount, 
        joinedCount 
      }, this.filterList);
      
    } catch (error) {
      console.error('【onShow】加载数据失败:', error);
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },
  onTabChange(e) {
    const index = Number(e.currentTarget.dataset.index);
    this.setData({ activeTab: index }, this.filterList);
  },
  filterList() {
    const { matchList, activeTab } = this.data;
    const app = getApp();
    const userInfo = app.globalData?.userInfo;
    let filtered = matchList;
    
    if (activeTab === 1) {
      // 我发起的
      filtered = matchList.filter(item => item.creator?.userId === userInfo?.userId);
      console.log('【filterList】我发起的 userId:', userInfo?.userId);
    } else if (activeTab === 2) {
      // 我参与的（包括帮别人报的）
      filtered = matchList.filter(item => item.isSigned);
      console.log('【filterList】我参与的 isSigned:', matchList.map(i => i.isSigned));
    }
    
    // 统计数量（防止切tab后数量不对）
    const allCount = matchList.length;
    const createdCount = matchList.filter(item => item.creator?.userId === userInfo?.userId).length;
    const joinedCount = matchList.filter(item => item.isSigned).length;
    console.log('【filterList】统计 allCount:', allCount, 'createdCount:', createdCount, 'joinedCount:', joinedCount);
    this.setData({ filteredList: filtered, allCount, createdCount, joinedCount });
  },
  onMatchTap(e) {
    // 如果当前有显示删除按钮，点击卡片时先隐藏
    if (this.data.showDeleteIndex !== null) {
      this.setData({ showDeleteIndex: null });
      return;
    }
    const id = e.currentTarget.dataset.id;
    
    // 获取比赛数据，判断比赛类型
    const localDataManager = require('../../utils/localDataManager.js');
    const raceData = localDataManager.getRace(id);
    
    let targetPage = '/pages/raceEnroll/raceEnroll'; // 默认跳转到多人轮转赛页面
    
    if (raceData && raceData.type === 'fixed') {
      // 固搭循环赛跳转到固搭页面
      targetPage = '/pages/fixedRace/fixedRace';
    } else if (raceData && raceData.type === 'single') {
      // 单打循环赛跳转到单打页面
      targetPage = '/pages/singlePlay/singlePlay';
    } else if (raceData && raceData.type === 'double_elimination') {
      // 双打淘汰赛跳转到双打淘汰赛页面
      targetPage = '/pages/doubleElimination/doubleElimination';
    }
    
    wx.navigateTo({
      url: `${targetPage}?id=${id}`
    });
  },
  onLongPressCard(e) {
    const id = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['删除'],
      itemColor: '#e64340',
      success: res => {
        if (res.tapIndex === 0) {
          wx.showModal({
            title: '确认删除',
            content: '删除后不可恢复，确定要删除吗？',
            success: modalRes => {
              if (modalRes.confirm) {
                this.deleteMatch(id);
              }
            }
          });
        }
      }
    });
  },
  onDeleteMatch(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '删除后不可恢复，确定要删除吗？',
      success: res => {
        if (res.confirm) {
          this.deleteMatch(id);
        }
      }
    });
  },
  deleteMatch(id) {
    try {
      // 引入本地数据管理器
      const localDataManager = require('../../utils/localDataManager.js');
      
      // 从本地存储删除比赛（会自动删除相关的报名记录）
      localDataManager.removeRace(id);
      
      wx.showToast({ title: '已删除' });
      this.onShow(); // 重新加载列表
      
    } catch (error) {
      console.error('删除比赛失败:', error);
      wx.showToast({ title: '删除失败', icon: 'none' });
    }
  }
});